package com.laicunba.ext.activity.act20170807;

import java.math.BigDecimal;
import java.util.Date;

import javax.jms.Message;
import javax.jms.TextMessage;

import org.apache.log4j.Logger;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.laicunba.ext.service.SlaveUserService;
import com.laicunba.jms.JmsQueueListener;
import com.laicunba.jms.JmsQueueListenerTemplate;
import com.laicunba.pojo.ActivityDO;
import com.laicunba.pojo.FinancingTargetBidDO;
import com.laicunba.pojo.UserDO;
import com.laicunba.service.ActivityService;
import com.laicunba.service.FinancingTargetBidService;
import com.laicunba.service.FinancingTargetService;
import com.laicunba.service.UserService;
import com.laicunba.service.VcoinWalletService;
import com.laicunba.util.CacheUtil;
import com.laicunba.util.DateUtil;
import com.laicunba.util.StringUtil;

/**
 * 2周年庆活动支付监听
 * 
 * @author lws
 *
 */
@Component
public class AnniversaryActivityInvestPaySuccessListener extends JmsQueueListenerTemplate implements JmsQueueListener {
	
	private static final Logger LOG = Logger.getLogger(AnniversaryActivityInvestPaySuccessListener.class);
	
	private static final String gather_activityId = "20170807";
	
	private static final String box_activityId = "20170814box";
	
	private static final String lottery_activityId = "20170814lottery";
	
	@Autowired
	private ActivityService activityService;
	
	@Autowired
	private FinancingTargetService financingTargetService;
	
	@Autowired
	private VcoinWalletService vcoinWalletService;
	
	@Autowired
	private FinancingTargetBidService financingTargetBidService;
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private SlaveUserService slaveUserService;

	@Override
	public String queue() {
		return "lcb.core.tmp.actpay8";
	}

	@Override
	public boolean receive(Message msg) {
		TextMessage txtMsg = (TextMessage) msg;
		try {
			LOG.info(String.format("【2周年庆活动】支付成功接收消息，txtMsg=[%s]", txtMsg.getText()));
			JSONObject msgJson = (JSONObject) new JSONParser().parse(txtMsg.getText());
			if (!msgJson.containsKey("id")) {
				return true;
			}
			String bidId = msgJson.get("id").toString();
			if(StringUtil.isEmpty(bidId)) {
				return true;
			}
			FinancingTargetBidDO bidDO = financingTargetBidService.get(FinancingTargetBidDO.class, bidId);
			if(bidDO == null || !"CPB".equalsIgnoreCase(bidDO.getType())) {
				return true;
			}
			// 防重复
			if (CacheUtil.incr("act.20170807." + bidDO.getId(), 60 * 10) > 1) {
				return true;
			}
			LOG.info(String.format("【2周年庆活动】支付成功接收消息，用户ID=[%s]", bidDO.getBidUserId()));
			if(StringUtil.isEmpty(bidDO.getBidUserId())) {
				return true;
			}
			UserDO bidUser = userService.get(UserDO.class, bidDO.getBidUserId());
			ActivityDO boxActivityDO = activityService.get(ActivityDO.class, box_activityId);
			// 获得积分 
			if (boxActivityDO != null && boxActivityDO.getBeginTime().before(new Date()) && boxActivityDO.getEndTime().after(new Date())) {
				int period = DateUtil.days(bidDO.getBeginProfit(), bidDO.getEndProfit());
				LOG.info(String.format("【2周年庆活动】支付成功接收消息，购买标的ID=[%s]，period=[%s]", bidId, period));
				if (period > 15) {
					// 对老活动的积分进行清零
					String currentUserIsCleared = CacheUtil.getAttribute("act.anniversary.20170807activity." + bidDO.getBidUserId() + ".clean-act20170703-vcoin");
					if (StringUtil.isEmpty(currentUserIsCleared) || !currentUserIsCleared.equals("1")) {
						long balance = vcoinWalletService.getBalance(bidDO.getBidUserId());
						if(balance > 0) {
							vcoinWalletService.subtract(bidDO.getBidUserId(), (int) balance, "CELEBRATE_DEPOSITORY_CLEAN", "2周年庆活动上线前积分清零");
						}
						CacheUtil.setAttribute("act.anniversary.20170807activity." + bidDO.getBidUserId() + ".clean-act20170703-vcoin", "1", 25 * 24 * 60 * 60);
					}
					
					int gainIntegral = 0;
					if (bidDO.getBuyAmount() != null) {
						gainIntegral = bidDO.getBuyAmount().multiply(BigDecimal.valueOf(period)).divide(BigDecimal.valueOf(365), BigDecimal.ROUND_HALF_UP).intValue();
					}
					
					LOG.info(String.format("【2周年庆活动】支付成功接收消息，购买标的ID=[%s]，period=[%s]，购买金额=[%s]，赠送积分=[%s]", bidId, period, bidDO.getBuyAmount(), gainIntegral));
					vcoinWalletService.add(bidUser.getId(), gainIntegral, "TWO_ANNIVERSARY_CELEBRATE_ONLINE", "2周年庆活动");
				}
			}
			// 首投
			boolean isFirstBuy = financingTargetBidService.isFirstBid(bidDO.getBidUserId());
			if(!isFirstBuy){
				return true;
			}
			if (StringUtil.isEmpty(bidUser.getInviteFrom())) {
				LOG.info(String.format("【2周年庆活动】支付成功接收消息，用户的邀请码为空，用户ID=[%s]", bidDO.getBidUserId()));
				return true;
			}
			UserDO friend = slaveUserService.findByInviteCode(bidUser.getInviteFrom());
			if(friend == null) {
				LOG.info(String.format("【2周年庆活动】支付成功接收消息，根据邀请码查询邀请人为空，邀请码=[%s]，用户ID=[%s]", bidUser.getInviteFrom(), bidDO.getBidUserId()));
				return true;
			}
			// 集结号获取邀请豆
			ActivityDO gatherActivityDO = activityService.get(ActivityDO.class, gather_activityId);
			if (bidUser.getChannel() != null && bidUser.getChannel().startsWith("no-award")) {
				if (gatherActivityDO != null && gatherActivityDO.getBeginTime().before(new Date()) && gatherActivityDO.getEndTime().after(new Date())) {
					//用户注册时间在活动时间范围
					if(bidUser.getGmtCreate().before(gatherActivityDO.getBeginTime()) || bidUser.getGmtCreate().after(gatherActivityDO.getEndTime()) ) {
						return true;
					}
					String currentInviteSoy = CacheUtil.getAttribute("act.anniversary.2017invitesoy." + friend.getId());
					int userInviteSoys = 0;
					if(StringUtil.isEmpty(currentInviteSoy)) {
						userInviteSoys = 1;
					} else {
						userInviteSoys = Integer.parseInt(currentInviteSoy) + 1;
					}
					CacheUtil.setAttribute("act.anniversary.2017invitesoy." + friend.getId(), String.valueOf(userInviteSoys), 25 * 24 * 60 * 60);
				}
			}
			
			// 青铜宝箱机会一次
			if (boxActivityDO != null && boxActivityDO.getBeginTime().before(new Date()) && boxActivityDO.getEndTime().after(new Date())) {
				//用户注册时间在活动时间范围
				if(bidUser.getGmtCreate().before(boxActivityDO.getBeginTime()) || bidUser.getGmtCreate().after(boxActivityDO.getEndTime()) ) {
					return true;
				}
				int openBoxChange = 0;
				String currentOpenBoxChange = CacheUtil.getAttribute("act.anniversary.2017openboxchange." + friend.getId());
				if (StringUtil.isEmpty(currentOpenBoxChange) || Integer.parseInt(currentOpenBoxChange) == 0) {
					openBoxChange = 1;
				} else {
					openBoxChange = Integer.parseInt(currentOpenBoxChange) + 1;
				}
				int days = DateUtil.days(boxActivityDO.getBeginTime(), boxActivityDO.getEndTime());
				CacheUtil.setAttribute("act.anniversary.2017openboxchange." + friend.getId(), 
						String.valueOf(openBoxChange), days * 24 * 60 * 60);
			}
			
			// 大转盘抽奖机会2次
			ActivityDO lotteryActivityDO = activityService.get(ActivityDO.class, lottery_activityId);
			if (lotteryActivityDO != null && lotteryActivityDO.getBeginTime().before(new Date()) && lotteryActivityDO.getEndTime().after(new Date())) {
				//用户注册时间在活动时间范围
				if(bidUser.getGmtCreate().before(lotteryActivityDO.getBeginTime()) || bidUser.getGmtCreate().after(lotteryActivityDO.getEndTime()) ) {
					LOG.info(String.format("【2周年庆活动】支付成功接收消息，用户未在活动时间范围内注册，用户ID=[%s]", bidDO.getBidUserId()));
					return true;
				}
				int lotteryDrawChange = 0;
				String currentLotteryDrawChance = CacheUtil.getAttribute("act.anniversary.2017lotterydrawchance." + friend.getId());
				if (StringUtil.isEmpty(currentLotteryDrawChance) || Integer.parseInt(currentLotteryDrawChance) == 0) {
					lotteryDrawChange = 1;
				} else {
					lotteryDrawChange = Integer.parseInt(currentLotteryDrawChance) + 1;
				}
				int days = DateUtil.days(boxActivityDO.getBeginTime(), boxActivityDO.getEndTime());
				CacheUtil.setAttribute("act.anniversary.2017lotterydrawchance." + friend.getId(), 
						String.valueOf(lotteryDrawChange), days * 24 * 60 * 60);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return true;
	}

}
